﻿using Admin.CommonLib.Models.User;
using FluentValidation;

namespace Admin.CommonLib.Validators
{
    public class UserEditValidator : AbstractValidator<UserEditRequestDto>
    {
        public UserEditValidator(Guid? key)
        {
            RuleFor(p => p.UserName)
                .NotEmpty()
                .WithMessage("用户名不能为空");

            RuleFor(p => p.RealName)
                .NotEmpty()
                .WithMessage("姓名不能为空");

            RuleFor(p => p.Email)
                .NotEmpty()
                .WithMessage("邮箱不能为空")
                .EmailAddress()
                .WithMessage("邮箱格式不正确");

            RuleFor(p => p.Password)
                .NotEmpty()
                .When(c => !key.HasValue)
                .WithMessage("密码不能为空");

            RuleFor(p => p.Phone)
                .NotEmpty()
                .WithMessage("联系方式不能为空");
        }

        public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
        {
            var result =
                await ValidateAsync(ValidationContext<UserEditRequestDto>.CreateWithOptions((UserEditRequestDto)model,
                    x => x.IncludeProperties(propertyName)));
            if (result.IsValid)
                return Array.Empty<string>();
            return result.Errors.Select(e => e.ErrorMessage);
        };
    }
}